import os
import sys
import subprocess
from flask import Flask, render_template, send_file
import tkinter as tk
from threading import Thread

app = Flask(__name__)

# 处理打包后的路径问题
def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

# 关键路径定义
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FFMPEG_PATH = resource_path(os.path.join('bin', 'ffmpeg.exe'))  # 动态路径
STREAM_DIR = os.path.join(BASE_DIR, 'static', 'stream')
os.makedirs(STREAM_DIR, exist_ok=True)

def start_capture(ffmpeg_cmd):
    return subprocess.Popen(ffmpeg_cmd, shell=True)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/stream/<filename>')
def stream(filename):
    return send_file(os.path.join(STREAM_DIR, filename))

# 图形化操作界面

# 前置参数
ffmpeg_cmd = [
    FFMPEG_PATH,
    '-f', 'gdigrab',
    '-framerate', '30',
    '-i', 'desktop',
    '-vf', 'scale=1920:-2',
    '-c:v', 'libx264',
    '-preset', 'veryfast',
    '-tune', 'zerolatency',
    '-f', 'hls',
    '-hls_time', '2',
    '-hls_list_size', '5',
    '-hls_flags', 'delete_segments',
    os.path.join(STREAM_DIR, 'stream.m3u8')
]
ipport = 54250
ipv4 = False

# 创建主窗口
root = tk.Tk()
root.title('ipv6投屏')
root.geometry('400x300')
root.resizable(False, False)

# ipv4勾选框
ipv4_var = tk.BooleanVar()
ipv4_var.set(False)

ipv4_button = tk.Checkbutton(root, text="使用IPv4而非ipv6", variable=ipv4_var)
ipv4_button.pack()
ipv4_button.place(x=50, y=150)

# 端口号输入框
ipport_var = tk.StringVar()
ipport_var.set('54250')

ipportlab = tk.Entry(root, textvariable=ipport_var, relief="sunken")
ipportlab.pack()
ipportlab.place(x=50, y=50, width=200, height=20)

# 帧率输入框
zhenlv_var = tk.StringVar()
zhenlv_var.set('30')

zhenlvlab = tk.Entry(root, textvariable=zhenlv_var, relief="sunken")
zhenlvlab.pack()
zhenlvlab.place(x=50, y=100, width=200, height=20)

# ipv6地址显示框
def get_ipv6_address1():
    try:
        # 调用ipconfig命令并获取其输出
        result = subprocess.run(['ipconfig'], capture_output=True, text=True, check=True)

        # 解析输出
        lines = result.stdout.split('\n')
        ipv6_addresses = []

        for line in lines:
            if '临时 IPv6 地址' in line:
                # 提取IPv6地址，通常位于冒号分隔的字符串中
                address = line.split(': ')[-1].strip()
                if address:  # 去除可能的空字符串
                    ipv6_addresses.append(address)

        # 如果没有找到IPv6地址，返回空列表
        if not ipv6_addresses:
            return None

        # 通常情况下，我们只关心第一个IPv6地址（取决于实际需求）
        return ipv6_addresses[0]

    except subprocess.CalledProcessError as e:
        print(f"Error occurred: {e}")
        return '未找到ipv6地址'

ipv6 = get_ipv6_address1()
ipv6_var = tk.StringVar()
ipv6lab = tk.Entry(root, textvariable=ipv6_var, state="readonly")
ipv6lab.pack()
ipv6lab.place(x=50, y=200, width=200, height=20)

# 增加一些描述
lab1 = tk.Label(root,text='端口号',relief='flat')
lab1.pack()
lab1.place(x=280, y=50)

lab2 = tk.Label(root,text='帧率',relief='flat')
lab2.pack()
lab2.place(x=280, y=100)

lab3 = tk.Label(root,text='ipv6地址',relief='flat')
lab3.pack()
lab3.place(x=280, y=200)

# 主按钮
def main():
    # 处理各实时变量
    ipv4 = ipv4_var.get()
    ip = '::'
    if ipv4:
        ip = '0.0.0.0'

    ipport = int(ipport_var.get())

    ffmpeg_cmd[4] = zhenlv_var.get()
    
    if not ipv4:
        ipv6_var.set('http://[' + ipv6 + ']:' + ipport_var.get())

    # 启动主程序
    ffmpeg_process = start_capture(ffmpeg_cmd)

    def run_flask():
        try:
            app.run(host=ip, port=ipport, debug=False)
        finally:
            ffmpeg_process.terminate()

    flask_thread = Thread(target=run_flask)
    flask_thread.daemon = True  # 设置为守护线程，确保主程序退出时子线程也会退出
    flask_thread.start()

# 定义按钮
buttonmain = tk.Button(root, text='开始投屏', command=main)
buttonmain.pack()
buttonmain.place(x=150, y=250, width=100, height=40)

# 运行应用程序
root.mainloop()
